<template>
  <ui-container class="single-transfer-pre">
    <span class="header-tabs-title">{{ headerTitle }}</span>
    <ui-tabs class="title-tabs" type="card" v-model="dealName" @tab-click="groupClick">
      <ui-tab-pane label="普通转账" name="singleTransferPre"></ui-tab-pane>
      <ui-tab-pane label="公益捐款" name="publicWelfarePre"></ui-tab-pane>
    </ui-tabs>
    <vx-title-bar current="1"></vx-title-bar>
    <vx-right-container>
      <div slot="left">
        <vx-collection-list
          v-loading="isContainerLoad"
          leftType="singleTransferPre"
          @leftInfo="assignment"
          @rightInfo="payerInfo"
        ></vx-collection-list>
      </div>
      <div slot="right">
        <ui-form ref="payer" :rules="rules" :model="payer" label-width="120px">
          <vx-form-container title="收款方信息">
            <ui-form-item prop="collAcNum" label="收款账号：">
              <ui-input-business type="bankCard" @blur="searchTrade" v-model="payer.collAcNum" placeholder="支持本行/他行账号"></ui-input-business>
            </ui-form-item>
            <!-- 收款名称 -->
            <ui-form-item prop="beneficiaryName" label="收款名称：">
              <ui-input v-model="payer.beneficiaryName" placeholder="请输入收款名称"></ui-input>
            </ui-form-item>
            <!-- 收款银行 -->
            <ui-form-item prop="bankDeposit" label="收款银行：" class="collect-bank">
              <div class="bank-label">
                <!--  收款银行弹框 -->
                <ui-autocomplete
                  v-model="payer.bankDeposit"
                  :fetch-suggestions="search"
                  :popper-append-to-body="false"
                  placeholder="请输入或选择收款银行"
                >
                  <span slot="suffix" class="search">
                    <img :src="require(`@/assets/image/theme/${activeName}/search.png`)" @click="showOutlets = true" />
                  </span>
                </ui-autocomplete>
              </div>
            </ui-form-item>
            <ui-form-item :key="isRequired" :prop="!isRequired ? '' : 'openingOutlets'" label="开户网点：" v-show="payer.bankDeposit && !isOwnTrade">
              <div class="bank-label">
                <!--  开户网点弹框 -->
                <ui-autocomplete
                  v-model="payer.openingOutlets"
                  :fetch-suggestions="searchOpeningOutlets"
                  :popper-append-to-body="false"
                  placeholder="请输入或选择开户网点"
                >
                  <span slot="suffix" class="search">
                    <img :src="require(`@/assets/image/theme/${activeName}/search.png`)" @click="showOpeningOutlets = true" />
                  </span>
                </ui-autocomplete>
              </div>
            </ui-form-item>
            <ui-form-item label=" ">
              <ui-checkbox v-model="isSaveGroup">保存至收款名册</ui-checkbox>
              <!-- 选择收款名册分组 -->
              <span class="selectClass">
                <ui-select
                  :popper-append-to-body="false"
                  class="group"
                  size="small"
                  filterable
                  v-model="membersValue"
                  placeholder="请选择"
                  :disabled="!isSaveGroup"
                >
                  <ui-option v-for="(item, index) in membersName" :key="index" :label="item.GroupName" :value="item.GroupNo"></ui-option>
                </ui-select>
              </span>
            </ui-form-item>
          </vx-form-container>
          <vx-form-container title="付款方信息">
            <!-- 付款账户 -->
            <ui-form-item prop="accountPayment" label="付款账户：">
              <ui-input-business type="bankCard" v-model="payer.accountPayment" placeholder="请在左侧选择付款账户" readonly></ui-input-business>
              <!-- 付款户名 -->
            </ui-form-item>
            <ui-form-item label="付款户名：">{{ payer.payerAcName }}</ui-form-item>
            <ui-form-item label="账户余额(元)：">{{ payer.money | numberFilter(2) }}</ui-form-item>
          </vx-form-container>
          <vx-form-container title="交易信息">
            <!-- 付款金额： -->
            <ui-form-item prop="amount" label="付款金额(元)：">
              <ui-input-business
                v-model="payer.amount"
                type="money"
                placeholder="请输入付款金额"
                :is-money-format="true"
                :maxlength="15"
              ></ui-input-business>
              <vx-explain-tips explain="限额说明" :isInput="true">
                <template>
                  <p>
                    <span>单笔限额</span>
                    {{ onceTranLimit | numberFilter(2) }}元
                  </p>
                  <p>
                    <span>日累计限额</span>
                    {{ dayTotalTranLimit | numberFilter(2) }}元
                  </p>
                  <p>
                    <span>剩余限额</span>
                    {{ dayRemainTranQuota | numberFilter(2) }}元
                  </p>
                  <p class="limit-explain-content">因存在待授权或待银行处理的指令，此限额仅作参考。</p>
                </template>
              </vx-explain-tips>
              <div class="form-notice" v-show="payer.amount != '' && payer.amount > 0">
                <span class="formality-class">手续费：{{ payer.serviceCharge | numberFilter(2) }}元</span>
                <vx-explain-tips explain="手续费说明" position>
                  <template
                    >跨行转账低于两千元的，每笔收取2元每笔费用。转账金额高于两千元的按转金额的0.3%收取人工费用，最低2元每笔，最高50元每笔封顶
                  </template>
                </vx-explain-tips>
                <p v-show="payer.amount != '' && payer.amount > 0">
                  {{ payer.amount | amountFilter }}
                </p>
              </div>
            </ui-form-item>
            <!-- 转账附言： -->
            <ui-form-item prop="postscript" label="转账附言：">
              <ui-select :popper-append-to-body="false" v-model="payer.postscript" placeholder="请选择" clearable>
                <ui-option v-for="(item, index) in postscriptTransferList" :key="index" :value="item.Purpose"></ui-option>
              </ui-select>
            </ui-form-item>
            <!-- 汇出类型： -->
            <ui-form-item label="汇出类型：">
              <ui-radio-group v-model="payer.exportType">
                <ui-radio
                  v-for="(item, index) in $field('exportTypeDict')"
                  :key="index"
                  :label="item.value"
                  :disabled="payer.amount > 1000000 && item.value == '0'"
                  >{{ item.label }}</ui-radio
                >
              </ui-radio-group>
            </ui-form-item>
            <!-- 短信通知 -->
            <ui-form-item prop="notice" label="短信通知：">
              <ui-input v-model="payer.notice" maxlength="11" placeholder="请输入手机号码"></ui-input>
            </ui-form-item>
            <ui-form-item label=" ">
              <ui-button class="default-btn" @click="onResetFormInfo('payer')">重置</ui-button>
              <ui-button class="primary-long-btn" @click="onConfirmFormInfo('payer')" :loading="isLoading">确定</ui-button>
            </ui-form-item>
          </vx-form-container>
        </ui-form>
      </div>
    </vx-right-container>
    <!-- 收款银行 -->
    <ui-dialog :visible.sync="showOutlets" width="50%" class="super-bank-dialog">
      <bank-deposit
        @SuperBankWay="superBankWay"
        @endSuperBankWay="
          (val) => {
            showOutlets = val;
          }
        "
      ></bank-deposit>
    </ui-dialog>
    <!-- 开户网点 -->
    <ui-dialog :visible.sync="showOpeningOutlets" width="1000px">
      <div slot="title" class="opening-outlets-dialog-title">
        <div>
          您已选择<span class="bank-name">&nbsp;{{ payer.bankDeposit }}</span
          >，请继续选择查询并选择开户网点
        </div>
      </div>
      <bank-opening-deposit @bankOpeningDepositSelected="changeOpeningOutlets"></bank-opening-deposit>
    </ui-dialog>
  </ui-container>
</template>
<script>
import transferRemitApi from '@/api/transferRemit';
import bankDeposit from '../components/bankDeposit'; // 收款银行
import bankOpeningDeposit from '../components/bankOpeningDeposit'; // 开户网点
import validate from '@/utils/validate';
import { mapState } from 'vuex';
let timer = '';
export default {
  data() {
    return {
      isOwnTrade: false, // 是否本行
      isRequired: false, // 超网控制 开户网点是否必选项
      isContainerLoad: false,
      isLoading: false,
      dealName: 'singleTransferPre', // tabs当前选中dealName
      membersName: [], // 收款人名称data数据
      membersValue: '', // 默认选中
      isSaveGroup: true, // 保存至收款名册
      postscriptTransferList: [], // 转账附言data数据
      showOutlets: false, // ui-dialog控制
      showOpeningOutlets: false, // ui-dialog控制
      bankList: [], // 查询银行
      onceTranLimit: '', // 单笔限额
      dayTotalTranLimit: '', // 日累计限额
      dayRemainTranQuota: '', // 日剩余限额
      payer: {
        collAcNum: '', // 收款账号
        beneficiaryName: '', // 收款名称
        bankDeposit: '', // 收款银行
        accountPayment: '', // 付款帐户
        payerAcName: '--', // 付款户名,
        amount: '', // 付款金额
        notice: '', // 短信通知
        money: '--', // 转出金额
        deptSetName: '', // 付款开户行
        exportType: '0', // 汇出类型
        postscript: '', // 转账附言
        openingOutlets: '', // 开户网点
        serviceCharge: '', // 手续费
      },
      rules: {
        collAcNum: [{ required: true, message: '请输入收款账号', trigger: 'change' }], // 收款账号
        beneficiaryName: [{ required: true, message: '请输入收款名称', trigger: 'change' }], // 收款名称
        bankDeposit: [{ required: true, message: '请输入或选择收款银行', trigger: 'change' }], // 收款银行
        accountPayment: [{ required: true, message: '请在左侧选择付款账户', trigger: 'change' }], // 付款帐户
        amount: [{ required: true, validator: validate.moneyRule, prefix: '付款金额', trigger: 'change' }], // 付款金额
        notice: [{ required: false, validator: validate.phoneRule, trigger: ['change', 'blur'] }], // 短信通知手机号
        openingOutlets: [{ required: true, message: '请输入或选择开户网点', trigger: 'change' }],
        postscript: [{ required: true, message: '请选择转账附言', trigger: 'change' }],
      },
    };
  },
  components: {
    bankDeposit,
    bankOpeningDeposit,
  },
  computed: {
    ...mapState('vxadmin/theme', ['activeName']),
  },
  watch: {
    // 切换tab,清空表单
    dealName() {
      this.onResetFormInfo('payer');
    },
    // 转账低于两千元的，每笔收取2元每笔费用。转账金额高于两千元的按转金额的0.3%收取费用
    'payer.amount'(newVal) {
      this.payer.serviceCharge = newVal > 2000 ? newVal * 0.003 : 2;
      this.isSupernetRequire(this.payer.bankDeposit, newVal);
      // 转账金额大于100万，不可选择实时汇出
      this.payer.exportType = newVal > 1000000 ? '1' : this.payer.exportType;
    },
    // 开户网点是否必选项
    async 'payer.bankDeposit'(newVal) {
      // 是否为本行
      let result = this.bankList.find((item) => {
        return item.value === newVal;
      });
      if (result) {
        this.isOwnTrade = result.isOwnTrade;
      }
      this.isSupernetRequire(newVal);
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      // 从确认页,转账交易查询,刷新页面 进入时,回显数据
      if (
        from.name === 'transferRemit-singleTransfer-singleTransferConf' ||
        (from.name === 'transferRemit-transTransaction-transferSingleQry' && vm.$route.query.flag) ||
        from.name === null
      ) {
        if (vm.getData() && vm.getData().dealName === 'singleTransferPre') {
          vm.payer = vm.getData();
        }
      }
    });
  },
  beforeRouteLeave(to, from, next) {
    if (to.name === 'transferRemit-singleTransfer-singleTransferConf') {
      from.meta.keepAlive = true;
    } else {
      from.meta.keepAlive = false;
    }
    next();
  },
  created() {
    // 首页账户信息点击转账跳转
    let accInfo = this.$route.params.accInfo;
    if (accInfo) {
      let res = {
        acNo: accInfo.accNo,
        AccountName: accInfo.accName,
        money: accInfo.accBalance,
        RealAdd: accInfo.realAdd,
      };
      this.payerInfo(res);
    }
  },
  async mounted() {
    try {
      this.isContainerLoad = true;
      let res = await Promise.all([transferRemitApi.getSaveGroup(), transferRemitApi.getTransferAmount(), transferRemitApi.searchBanks()]);
      // 收款人名册分组
      this.membersName = res[0].List;
      this.membersValue = this.membersName[0].GroupNo;
      // 获取转账附言列表
      this.postscriptTransferList = res[1].List;
      // 查询收款银行
      this.bankList = res[2].list;
    } catch (err) {
      this.$message.error(err.message);
    } finally {
      this.isContainerLoad = false;
    }
  },
  methods: {
    // 查询收款银行
    async search(queryStr, cb) {
      try {
        this.isLoading = true;
        let res = await transferRemitApi.searchBanks();
        this.bankList = res.list;
        if (cb) {
          cb(queryStr ? this.bankList.filter(this.createStateFilter(queryStr)) : this.bankList);
        }
      } catch (err) {
        this.$message.error(err.message);
      } finally {
        this.isLoading = false;
      }
    },
    // 筛选
    createStateFilter(queryStr) {
      return (state) => state.value.toLowerCase().indexOf(queryStr.toLowerCase()) === 0;
    },
    isSupernetRequire(bankDeposit = this.payer.bankDeposit, amount = this.payer.amount) {
      let result = this.bankList.find((item) => {
        return item.value === bankDeposit;
      });
      // 非超网 或者 如果收款银行属于超网，但是转账金额超过100万，开户网点必输。
      if (!result || !result.isSupernet || (result && result.isSupernet && amount >= 1000000)) {
        this.isRequired = true;
      } else {
        this.isRequired = false;
      }
    },
    // 查询是否是本行账户。为本行账户时,不展示开户网点
    searchTrade() {
      // 加延时为了 未失焦时,其他事件触发时,触发失焦和此事件
      timer = setTimeout(async () => {
        try {
          this.isContainerLoad = true;
          let result = await transferRemitApi.searchTrade(this.payer.collAcNum);
          this.payer.bankDeposit = result.accountInfo.bankDeposit;
          this.isOwnTrade = result.accountInfo.isOwnTrade;
        } catch (err) {
          this.$message.error(err.message);
        } finally {
          this.isContainerLoad = false;
        }
      }, 100);
    },
    // 收款账户点击
    assignment(res) {
      this.payer.collAcNum = res.acNo;
      this.payer.beneficiaryName = res.name;
      this.payer.bankDeposit = res.bankName;
    },
    // 付款账户点击
    async payerInfo(res) {
      this.payer.accountPayment = res.acNo;
      this.payer.payerAcName = res.AccountName;
      this.payer.money = res.money;
      this.payer.deptSetName = res.RealAdd;
      try {
        this.isLoading = true;
        // 查询账户限额
        let res = await transferRemitApi.getPRLimitQry(this.payer);
        this.onceTranLimit = res.onceTranLimit; // 单笔限额
        this.dayTotalTranLimit = res.dayTotalTranLimit; // 日累计限额
        this.dayRemainTranQuota = res.dayRemainTranQuota; // 日剩余限额
      } catch (err) {
        this.$message.error(err.message);
      } finally {
        this.isLoading = false;
      }
    },
    // 重置信息
    onResetFormInfo(formName) {
      this.$refs[formName].resetFields();
      this.payer.payerAcName = '--';
      this.payer.money = '';
      this.clearData();
    },
    // 确认信息
    onConfirmFormInfo(formName) {
      if (this.payer.collAcNum && this.payer.collAcNum === this.payer.accountPayment) {
        return this.$message.error('收款账号不能与付款账号相同');
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.payer.money < Number(this.payer.amount)) {
            this.$confirm('转账金额大于当前账户可用余额，请确保交易指令审核通过发出时，账户余额充足，否则将转账失败', '余额不足提醒', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              cancelButtonClass: 'default-btn', // 取消按钮的自定义类名
              type: 'warning',
            }).then(() => {
              this.confirmSure();
            });
            // 即使余额不足也可以发起交易
          } else {
            this.confirmSure();
          }
        } else {
          this.$nextTick(() => {
            document
              .querySelectorAll('.is-error')[0]
              .querySelector('input')
              .focus();
          });
        }
      });
    },
    // 调用confirm接口
    async confirmSure() {
      try {
        this.isLoading = true;
        await transferRemitApi.transactionInformation(this.payer);
        // 防重复提交-获取token
        await this.getToken('/resultDetail.do');
        this.setData({
          ...this.payer,
          dealName: 'singleTransferPre',
        });
        this.$router.push({
          name: 'transferRemit-singleTransfer-singleTransferConf',
        });
      } catch (err) {
        this.$message.error(err.message);
      } finally {
        this.isLoading = false;
      }
    },
    // 菜单栏切换
    groupClick(tab) {
      this.$router.replace({
        name: 'transferRemit-singleTransfer-' + tab.name,
      });
    },
    // 选择开户行回显
    superBankWay(val) {
      this.payer.bankDeposit = val.BankName;
      this.showOutlets = false;
    },
    // 开户网点选择
    changeOpeningOutlets(item) {
      this.payer.openingOutlets = item.value;
      this.showOpeningOutlets = false;
    },
    // 查询开户网点
    async searchOpeningOutlets(queryStr, cb) {
      try {
        this.isLoading = true;
        let res = await transferRemitApi.searchOpeningOutlets();
        this.openingOutlets = res.list;
        cb(queryStr ? this.openingOutlets.filter(this.createStateFilter(queryStr)) : this.openingOutlets);
      } catch (err) {
        this.$message.error(err.message);
      } finally {
        this.isLoading = false;
      }
    },
  },
  beforeDestroy() {
    clearTimeout(timer);
  },
};
</script>
<style lang="scss">
.single-transfer-pre {
  .super-bank-dialog .ui-dialog {
    min-width: 600px;
    max-width: 800px;
  }
  .selectClass {
    padding-left: 30px;
    .ui-select .ui-input__inner {
      width: 100px;
    }
  }
  .opening-outlets-dialog-title {
    box-sizing: border-box;
    position: absolute;
    top: 0;
    left: 0;
    height: 60px;
    width: 100%;
    line-height: 4;
    align-items: center;
    padding: 0 40px;
    color: $color-text-main;
    background: $color-bg-btn-info-active;
    .bank-name {
      color: #000;
      font-weight: $font-weight-medium;
    }
  }
}
</style>
